<template>
  <el-select v-model="internalValue" filterable class="width-100" @change="onChange">
    <el-option
      v-for="option in options" :key="option.id"
      :label="option.code + '-' + option.name"
      :value="option.id"
    ></el-option>
  </el-select>
</template>

<script>
import { queryEnergyUseList } from '@/api/energyUse'

export default {
  inheritAttrs: false,
  name: 'energy-purpose-picker',
  props: {
    value: [String, Number],
  },
  data () {
    return {
      internalValue: this.value ? Number(this.value) : '',
      options: [],
    }
  },
  watch: {
    value (val) {
      this.internalValue = val
    },
  },
  mounted () {
    this.getOptions()
  },
  methods: {
    onChange (value) {
      const option = this.options.find(v => v.id === value)
      const name = option ? option.name : ''
      this.$emit('input', value)
      this.$emit('change', { value, name, option })
    },
    getOptions () {
      return queryEnergyUseList().then(res => {
        if (res.code === 200) {
          this.options = res.data
        }
      })
    },
  },
}
</script>
